package de.koller.gravity.mech.universe;

import de.koller.gravity.mech.particle.Particle;
import de.koller.gravity.mech.particle.ParticleEngine;
import de.koller.gravity.mech.particle.environment.IParticleEnvironment;
import de.koller.oceanFramework.math.RVec3d;

public class GravitationEnvironment implements IParticleEnvironment {

	public static final double G = 0.0001;
	
	@Override
	public void stepParticle( Particle p, ParticleEngine engine ) {
		if( p instanceof PlanetaryMass == false )
			return;
		
		for( Particle o : engine.particles ) {
			if( o == p )
				continue;
			if( o instanceof PlanetaryMass == false )
				continue;
		
			RVec3d f = getForce( (PlanetaryMass)p, (PlanetaryMass)o );
			f.div( ((PlanetaryMass)p).getMass() ); 
			p.velocity.add( f );
		}
	}
	
	public static RVec3d getForce( PlanetaryMass p1, PlanetaryMass p2 ) {
		RVec3d rv = RVec3d.difference( p2.position, p1.position );
		
		double le = rv.getLengthSquared();
		double mass = (p1.getMass()*p2.getMass());
		
		if( le < MoltPlanet.MOLT_RANGE_SQUARED + p1.size*.5 + p2.size*.5 )
			return new RVec3d();
		
		double f = G * ( mass / le );
		rv.setLength2D( f );
		return rv;
	}

}
